package com.hgkj.cloud.customer.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hgkj.cloud.base.common.AdminCommon;
import com.hgkj.cloud.base.common.PageInfo;
import com.hgkj.cloud.customer.common.AjaxJson;
import com.hgkj.cloud.customer.common.DataGrid;
import com.hgkj.cloud.customer.util.DateTimeUtil;
import com.hgkj.cloud.customer.util.DateUtil;
import com.hgkj.cloud.base.domain.SysTenants;
import com.hgkj.cloud.base.domain.TenantFrameworks;
import com.hgkj.cloud.base.domain.TenantQuestionnaires;
import com.hgkj.cloud.base.domain.TenantUsers;
import com.hgkj.cloud.base.service.*;
import org.apache.commons.io.IOUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

@Controller
@RequestMapping("/ctwarning")
public class CustomTableWarningController extends BaseController {

	@Autowired
	private TenantQuestionnairesService tenantQuestionnairesService;
	@Autowired
	private SysTenantsService sysTenantsService;
	@Autowired
	private SysTableFactorDictService sysTableFactorDictService;
	@Autowired
	private TenantQuestionnaireTaskInfoService tenantQuestionnaireTaskInfoService;
	@Autowired
	private TenantFrameworksService tenantFrameworksService;
	@Autowired
	private TenantQuestionnaireQuestionService tenantQuestionnaireQuestionService;
	@Autowired
	private TenantLogsService tenantLogsService;

	/**
	 * 自定义量表列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("getctlist")
	@ResponseBody
	public List<TenantQuestionnaires> getCustomTableList(HttpServletRequest request, Long tenant_id, String user_id) {
		AjaxJson aj = new AjaxJson();
//		User user = (User) SecurityUtils.getSubject().getPrincipal();
		TenantUsers user = getUserInfoById(user_id);
		Map<String, Object> map = new HashMap<String, Object>();
//		getCustom(request,user);
		boolean isGetTop = (boolean) request.getSession().getAttribute("is_get_top");
		List<Long> tenant_ids = getSonTenantIds(tenant_id);
		if(tenant_ids!=null) {
			if(isGetTop) {
				Long top_tenant_id = user.getTop_tenant_id();
				tenant_ids.add(top_tenant_id);
			}
			tenant_ids.add(tenant_id);
			map.put("tenant_ids", tenant_ids);
		}else {
			List<Long> mtenant_ids =new ArrayList<>();
			if (isGetTop) {
				mtenant_ids.add(user.getTop_tenant_id());
			}
			mtenant_ids.add(tenant_id);
			map.put("tenant_ids", mtenant_ids);
		}

		List<TenantQuestionnaires> questionnaires = tenantQuestionnairesService.findQuestionnaireByTenantId(map);
		return questionnaires;
	}

//	/**
//	 * 获取预警分数
//	 *
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping("getctwaringscore")
//	@ResponseBody
//	public AjaxJson getCustomTableWaringScore(HttpServletRequest request, Long questionnaire_id) {
//		AjaxJson aj = new AjaxJson();
//		Map<String, Object> map = new HashMap<String, Object>();
//		Questionnaire questionnaire = questionnaireService.findQuestionnaireById(questionnaire_id);
//		Map<String, Object> p_map = new HashMap<String, Object>();
//		p_map.put("waringscore", questionnaire.getWaring_score());
//		aj.setAttributes(p_map);
//		return aj;
//	}

	/**
	 * 设置预警分数
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("setctwaringscore")
	@ResponseBody
	public AjaxJson setCustomTableWaringScore(HttpServletRequest request, Long questionnaire_id, Double waringscore,
											  String tag_string) {
		AjaxJson aj = new AjaxJson();
		TenantQuestionnaires questionnaire = new TenantQuestionnaires();
		questionnaire.setWaring_score(waringscore);
		questionnaire.setId(questionnaire_id);
		questionnaire.setTag_string(tag_string);
		int qn = tenantQuestionnairesService.updateByPrimaryKeySelective(questionnaire);
		Map<String, Object> p_map = new HashMap<String, Object>();
		p_map.put("sucess", qn);
		aj.setAttributes(p_map);
		return aj;
	}

//	/**
//	 * 弹出框分页 查询表头人员信息
//	 */
//	@RequestMapping("/warningUsersInfosTitle")
//	@ResponseBody
//	public DataGrid warningUsersInfosTitle(DataGrid dataGrid, Double waring_score, Long tenant_id,Long framework_id,
//			String questionnaire_id, String test_begin_date, String test_end_date, Integer datetype,Integer isWaring) {
//		// Map<String, Object> data =this.cirsesWarningCounts(tenant_id,
//		// questionnaire_id, test_begin_date, test_end_date, datetype);
//		// Map<String, Object> map = new HashMap<>();
//		PageInfo pi = new PageInfo();
//		Map<String, Object> map = new HashMap<String, Object>();
//		Map<String, Object> p_map = new HashMap<String, Object>();
//		Map<String, Integer> count_map = new HashMap<String, Integer>();
//		p_map.put("questionnaire_id", questionnaire_id);
//		if (dataGrid.getPage() > 0) {
//			pi.setCurrentPage(dataGrid.getPage());
//			pi.setPageSize(Integer.parseInt(dataGrid.getRows().get(0).toString()));
//		}
//		// System.out.println("test_begin_date="+test_begin_date);
//		// System.out.println("test_end_date="+test_end_date);
//		if(isWaring ==1) {
//			p_map.put("isWaring", 1);
//		}
//		if(isWaring ==0) {
//			p_map.put("isWaring", 0);
//		}
//		if (datetype != 0) {
//			test_begin_date = DateUtil.dateBack(datetype);
//			test_end_date = null;
//		}
//		p_map.put("waring_score", waring_score);
//		if (test_begin_date != null && test_begin_date != "") {
//			p_map.put("test_begin_date", test_begin_date);
//		}
//		if (test_end_date != null && test_end_date != "") {
//			p_map.put("test_end_date", test_end_date);
//		}
//		if(tenant_id!=null  ) {
//			Tenant tenant = tenantService.getTenantById(tenant_id);
//			// 统计深度，大租户时本登陆单位等级减1，小租户时最小为1，最大为2；
//			if (tenant.getTenant_level() == 1) {
//				p_map.put("tenant_id", tenant_id);
//			} else {
//				List<Long> tenant_ids = this.getSonTenantIds(tenant_id);
//				p_map.put("tenant_ids", tenant_ids);
//			}
//		}
//		if(framework_id!=null) {
//			p_map.put("framework_id", framework_id);
//		}
//		List<Map<String, Object>> data = questionnaireService.listWarningUsers(pi,p_map);
//		int dataSize=questionnaireService.listWarningUsersCount(p_map);
//		long longdataSize=new Long((long)dataSize);
//		dataGrid.setRows(data);
//		dataGrid.setTotal(longdataSize);
//		return dataGrid;
//	}
//
//	/**
//	 * 导出预警人员信息
//	 *
//	 * @throws IOException
//	 */
//	@RequestMapping("/exportChengduBody")
//	public String exportChengduBody(Double waring_score, Long tenant_id,Long framework_id, String questionnaire_id,
//			String test_begin_date, String test_end_date, Integer datetype, HttpServletRequest request,Integer isWaring,
//			HttpServletResponse response,String user_id) throws IOException {
////		User operator = (User) SecurityUtils.getSubject().getPrincipal();
//		TenantUsers operator = getUserInfoById(user_id);
//		String fileName = "userinfo";
//		response.setContentType("application/vnd.ms-excel;charset=utf-8");
//		response.setHeader("Content-Disposition",
//				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
//		Map<String, Object> p_map = new HashMap<String, Object>();
//		p_map.put("questionnaire_id", questionnaire_id);
//		PageInfo pi = new PageInfo();
//		// System.out.println("test_begin_date="+test_begin_date);
//		// System.out.println("test_end_date="+test_end_date);
//		if(isWaring ==1) {
//			p_map.put("isWaring", 1);
//		}
//		if(isWaring ==0) {
//			p_map.put("isWaring", 0);
//		}
//		if (datetype != 0) {
//			test_begin_date = DateUtil.dateBack(datetype);
//			test_end_date = null;
//		}
//		p_map.put("waring_score", waring_score);
//		if (test_begin_date != null && test_begin_date != "") {
//			p_map.put("test_begin_date", test_begin_date);
//		}
//		if (test_end_date != null && test_end_date != "") {
//			p_map.put("test_end_date", test_end_date);
//		}
//		if(tenant_id!=null  ) {
//			SysTenants tenant = sysTenantsService.getSimpleTenantById(tenant_id);
//			// 统计深度，大租户时本登陆单位等级减1，小租户时最小为1，最大为2；
//			if (tenant.getTenant_level() == 1) {
//				p_map.put("tenant_id", tenant_id);
//			} else {
//				List<Long> tenant_ids = this.getSonTenantIds(tenant_id);
//				p_map.put("tenant_ids", tenant_ids);
//			}
//		}
//		if(framework_id!=null) {
//			p_map.put("framework_id", framework_id);
//		}
//		List<Map<String, Object>> data = tenantQuestionnaireTaskInfoService.listWarningUsers(null,p_map);
//		try {
//			if (data.size() != 0) {
//				TenantQuestionnaires mQuestionnaire = tenantQuestionnairesService.findQuestionnaireById(Long.valueOf(questionnaire_id));
//				int mQuestionSum=	mQuestionnaire.getQuestion_sum();
//				List<Map<String, Object>> mQUandAnScoreList = tenantQuestionnaireQuestionService.getQUandAnScore(questionnaire_id);
//				for (int i = 0; i < data.size(); i++) {
//					String[] dataStr=data.get(i).get("answer").toString().split("\\|");
//					for (int j = 0; j < dataStr.length; j++) {
//						String an=dataStr[j];
//						if(operator.getTop_tenant_id().equals(342L)&&questionnaire_id.equals("46")&&j>=dataStr.length-4) {
//							data.get(i).put("score"+j, an);
//						}else {
//							if(an.contains(",")) {
//								data.get(i).put("score"+j, an);
//							}else {
//								for (int k = 0; k < mQUandAnScoreList.size(); k++) {
//									if((mQUandAnScoreList.get(k).get("qu_id").toString()).equals((1+j)+"")) {
//										if((mQUandAnScoreList.get(k).get("an_id").toString()).equals(an)) {
//											String score = String.valueOf(mQUandAnScoreList.get(k).get("score"));
//											data.get(i).put("score"+j, score);
//										}
//									}
//								}
//							}
//
//
//						}
//
//					}
//				}
//				jsWwriteExcel(mQuestionSum,data, response);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//			//writeExcel(data, response);
//
//		return null;
//	}

//	// 导出excel
//	public void writeExcel(List<Map<String, Object>> list, HttpServletResponse response) {
//		OutputStream os = null;
//		try {
//			os = response.getOutputStream();
//			WritableWorkbook wwb = null;
//			// 创建可写入的Excel工作簿
//			wwb = Workbook.createWorkbook(os);
//			WritableSheet ws = wwb.createSheet("人员表", 0);
//			Label labelName = new Label(0, 0, "用户名");// 表示横着有几个
//			Label real_name = new Label(1, 0, "真实姓名");
//			Label user_gender = new Label(2, 0, "性别");
//			Label user_birth = new Label(3, 0, "出生日期");
//			Label frame_work = new Label(4, 0, "组织机构");
//			Label score = new Label(5, 0, "总分");
//			Label answer = new Label(6, 0, "答案");
//			Label submit_date = new Label(7, 0, "提交时间");
//			ws.addCell(labelName);
//			ws.addCell(real_name);
//			ws.addCell(user_gender);
//			ws.addCell(user_birth);
//			ws.addCell(frame_work);
//			ws.addCell(score);
//			ws.addCell(answer);
//			ws.addCell(submit_date);
//			for (int i = 0; i < list.size(); i++) {
//				// System.out.println(list.get(i).get("user_name"));
//				Label labelName_i = new Label(0, i + 1, list.get(i).get("user_name").toString());
//				Label real_name_i = new Label(1, i + 1, list.get(i).get("real_name").toString());
//				Label user_gender_i = new Label(2, i + 1,
//						AdminCommon.getGenderString((Integer) list.get(i).get("user_gender")));
//				Label user_birth_i = new Label(3, i + 1,
//						DateTimeUtil.getStringFromUTC((Long) list.get(i).get("user_birth")));
//				Label frame_work_i = new Label(4, i + 1, list.get(i).get("whole_name").toString());
//				Label score_i = new Label(5, i + 1, list.get(i).get("score").toString());
//				Label answer_i = new Label(6, i + 1, list.get(i).get("answer").toString());
//				Label submit_date_i = new Label(7, i + 1, list.get(i).get("submit_date").toString());
//				ws.addCell(labelName_i);
//				ws.addCell(real_name_i);
//				ws.addCell(user_gender_i);
//				ws.addCell(user_birth_i);
//				ws.addCell(frame_work_i);
//				ws.addCell(score_i);
//				ws.addCell(answer_i);
//				ws.addCell(submit_date_i);
//			}
//			// 写进文档
//			wwb.write();
//			wwb.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			IOUtils.closeQuietly(os);
//		}
//	}

	/**
	 * 按条件查询 create by
	 */
	@RequestMapping("/findStudentByParameter")
	@ResponseBody
	public DataGrid findStudentByParameter(DataGrid dataGrid, String questionnaire_id, String user_name, String real_name, Integer user_gender,
										   Long tenant_id, Long framework_id, Double minScore, Double maxScore, Integer level, String user_id) {
//		User operator = (User) SecurityUtils.getSubject().getPrincipal();
		TenantUsers operator = getUserInfoById(user_id);
		Map<String, Object> p_map = new HashMap<String, Object>();
		p_map.put("questionnaire_id", questionnaire_id);
		PageInfo pi = new PageInfo();
		Map<String, Object> map = new HashMap<String, Object>();
		if (dataGrid.getPage() > 0) {
			pi.setCurrentPage(dataGrid.getPage());
			pi.setPageSize(Integer.parseInt(dataGrid.getRows().get(0).toString()));
		}

		Map<String, Object> testMap = new HashMap<>();

		if (user_gender != null) {
			p_map.put("user_gender", user_gender);
		}
		if (!StringUtils.isEmpty(user_name)) {
			p_map.put("user_name", user_name);
		}
		if (!StringUtils.isEmpty(real_name)) {
			p_map.put("real_name", real_name);
		}
		if(minScore!=null )
		p_map.put("minScore", minScore);
		if(maxScore!=null )
		p_map.put("maxScore", maxScore);

		List<Long> framework_ids = new ArrayList<>();
		List<Long> tenant_ids = new ArrayList<>();

		if(level == null) {
			if(tenant_id!=null) {
				tenant_ids=	this.getSonTenantIds(tenant_id);
				if(tenant_ids!=null) {
					tenant_ids.add(tenant_id);
					p_map.put("tenant_ids", tenant_ids);
				}else {
					p_map.put("tenant_id", tenant_id);
				}
			}
			if(framework_id!=null) {
				TenantFrameworks framework = tenantFrameworksService.getFrameworkById(framework_id);
				framework_ids = getFrameworkIdsByFatherId(framework_id, framework.getTenant_id());
				if(framework_ids!=null) {
					framework_ids.add(framework_id);
						p_map.put("framework_ids", framework_ids);
				}else {
					p_map.put("framework_id", framework_id);
				}
			}
		}else if(level==-1) {
			// 当登陆单位是大租户并且点击了下级单位时执行此步骤
			framework_ids = this.getSonTenantIds(framework_id);
			p_map.put("tenant_ids", framework_ids);
		}

		List<Map<String, Object>> data = tenantQuestionnaireTaskInfoService.listUsersByParameter(pi,p_map);
			int dataSize =  tenantQuestionnaireTaskInfoService.listUsersByParameterCount(p_map);
			long longdataSize=new Long((long)dataSize);
			// questionnaireService
			dataGrid.setRows(data);
			dataGrid.setTotal(longdataSize);
		return dataGrid;
	}

//	/**
//	 * 导出统计出来的用户
//	 */
//	@RequestMapping("/exportExcelUser22")
//	public String exportExcelUser(String questionnaire_id, String user_name, String real_name, Integer user_gender,
//			 Integer level,Long tenant_id,Long framework_id, Double minScore, Double maxScore, HttpServletRequest request,
//			HttpServletResponse response) throws IOException {
//		User operator = (User) SecurityUtils.getSubject().getPrincipal();
//		String fileName = "userinfoReport";
//		response.setContentType("application/vnd.ms-excel;charset=utf-8");
//		response.setHeader("Content-Disposition",
//				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
//		// response.setHeader("Content-Disposition", "attachment;filename=\""+ new
//		// String(fileName.getBytes("gb2312"),"iso-8859-1")+".xls"+"\"");
//		// 根据传进来的file对象创建可写入的Excel工作薄
//		Map<String, Object> p_map = new HashMap<String, Object>();
//		p_map.put("questionnaire_id", questionnaire_id);
//		/* testMap.put("tenant_id", 1); */
//		if (user_gender != null) {
//			p_map.put("user_gender", user_gender);
//		}
//		if (user_name != null && user_name != "") {
//			p_map.put("user_name", user_name);
//		}
//		if (real_name != null && real_name != "") {
//			p_map.put("real_name", real_name);
//		}
//		p_map.put("minScore", minScore);
//		p_map.put("maxScore", maxScore);
//
//		Tenant tenanttemp=new Tenant();
//		tenanttemp=tenantService.getTenantById(operator.getTenant_id());
//		List<Long> framework_ids = new ArrayList<>();
//		List<Long> tenant_ids = new ArrayList<>();
//
//		if(level == null) {
//			if(tenant_id!=null) {
//				tenant_ids=	this.getSonTenantIds(tenant_id);
//				if(tenant_ids!=null) {
//					tenant_ids.add(tenant_id);
//					p_map.put("tenant_ids", tenant_ids);
//				}else {
//					p_map.put("tenant_id", tenant_id);
//				}
//			}
//			if(framework_id!=null) {
//				Framework framework=tenantService.getFrameworkById(framework_id);
//				framework_ids = getFrameworkIdsByFatherId(framework_id, framework.getTenant_id());
//				if(framework_ids!=null) {
//					framework_ids.add(framework_id);
//						p_map.put("framework_ids", framework_ids);
//				}else {
//					p_map.put("framework_id", framework_id);
//				}
//			}
//		}else if(level==-1) {
//			// 当登陆单位是大租户并且点击了下级单位时执行此步骤
//			framework_ids = this.getSonTenantIds(framework_id);
//			p_map.put("tenant_ids", framework_ids);
//		}
//		/*if (level == null) {
//			// 任何等级租户刚进入（无点击操作时或者点击了组织结构时）level都为NULL，framework_id也为NUll,执行此步骤
//			if (framework_id == null) {
//				framework_ids = this.getSonTenantIds(operator.getTenant_id());
//				p_map.put("tenant_ids", framework_ids);
//			} else {
//				// 判断当前用户是否为顶级,顶级用户Father_id为0
//				Framework fra = tenantService.getFrameworkById(framework_id);
//				if (fra != null && fra.getFather_id() == 0) {
//					framework_ids = this.getSonTenantIds(fra.getTenant_id());
//					p_map.put("tenant_ids", framework_ids);
//				} else {
//					framework_ids = getFrameworkIdsByFatherId(framework_id, framework.getTenant_id());
//					p_map.put("tenant_id", operator.getTenant_id());
//					p_map.put("framework_ids", framework_ids);
//				}
//			}
//		} else {
//
//			if (level == 1 || level == -1) {
//				p_map.put("tenant_id", framework_id);
//			} else {
//				// 当登陆单位是大租户并且点击了下级单位时执行此步骤
//				framework_ids = this.getSonTenantIds(framework_id);
//				p_map.put("tenant_ids", framework_ids);
//			}
//		}*/
//		/*if(tenant_id!=null  ) {
//			Tenant tenant = tenantService.getTenantById(tenant_id);
//			// 统计深度，大租户时本登陆单位等级减1，小租户时最小为1，最大为2；
//			if (tenant.getTenant_level() == 1) {
//				p_map.put("tenant_id", tenant_id);
//			} else {
//				List<Long> tenant_ids = this.getSonTenantIds(tenant_id);
//				p_map.put("tenant_ids", tenant_ids);
//			}
//		}
//		if(framework_id!=null) {
//			p_map.put("framework_id", framework_id);
//		}*/
//		List<Map<String, Object>> data = questionnaireService.listUsersByParameter(null,p_map);
//
//		if (data.size() != 0) {
//			writeExcel(data, response);
//		}
//		// 日志
//		String operation = operator.getUser_name() + AdminCommon.COMMON_EXPORT + "统计人员信息表";
//		logService.insertLog(operator.getId(), operator.getTenant_id(), "user", operation);
//		return null;
//	}

	/*
	 * 进入到预警表格页面
	 */
//	@RequestMapping(value = "/gotocirsesWarning")
//	@ResponseBody
//	public Map<String, Object> gotocirsesWarning(HttpServletRequest request,String user_id) {
//		Map<String, Object> map = new HashMap<String, Object>();
////		User user = (User) SecurityUtils.getSubject().getPrincipal();
//		TenantUsers user = getUserInfoById(user_id);
//		SysTenants tenant = sysTenantsService.getSimpleTenantById(user.getTenant_id());
////		Tenant tenant = tenantService.getTenantById(user.getTenant_id());
//		Map<String, Object> maptemp = new HashMap<String, Object>();
//		maptemp.put("customer_type", tenant.getTenant_type_code());
//		map.put("tablelist", sysTableFactorDictService.listTableAnalyzeTables(maptemp));
//		int lev = 0;
//		// 统计深度，大租户时本登陆单位等级减1，小租户时最小为1，最大为2；
//		if (tenant.getTenant_level() == 1) {
//			lev = getLevel(user.getTenant_id());
//			if (lev == 0) {
//				lev = 1;
//			}
//			if (lev > 2) {
//				lev = 2;
//			}
//		} else {
//			lev = tenant.getTenant_level() - 1;
//		}
//		map.put("levels", lev); // 当前登陆单位的等级
//		map.put("tenantlevel", tenant.getTenant_level());
//		map.put("tenantname", tenant.getTenant_name());
//		map.put("tenant_typecode", tenant.getTenant_type_code());
//		map.put("tenant_id", tenant.getId());
//		return map;
////		return new ModelAndView("manager/questionnaire/customerWarningTables", map);
//	}

	/*
	 * 进入到预警报告查询
	 */
	@RequestMapping(value = "/gotoSelWarning")
	@ResponseBody
	public Map<String, Object> gotoSelWarning(HttpServletRequest request,String user_id) {
		Map<String, Object> map = new HashMap<String, Object>();
//		User user = (User) SecurityUtils.getSubject().getPrincipal();
		TenantUsers user = getUserInfoById(user_id);
		SysTenants tenant = sysTenantsService.getSimpleTenantById(user.getTenant_id());
		Map<String, Object> maptemp = new HashMap<String, Object>();
		maptemp.put("customer_type", tenant.getTenant_type_code());
		map.put("tablelist", sysTableFactorDictService.listTableAnalyzeTables(maptemp));
		if ("school".equals(tenant.getTenant_type_code())) {
			List<String> levels = new ArrayList<String>();
			if (tenant.getTenant_level() == 1) { // 小租户只取最后三级统计
				for (int i = AdminCommon.TABLE_ANALYZE_SCHOOL_LEVEL.length
						- 3; i < AdminCommon.TABLE_ANALYZE_SCHOOL_LEVEL.length; i++)
					levels.add(AdminCommon.TABLE_ANALYZE_SCHOOL_LEVEL[i]);
			} else { // 大租户根据当前租户等级，一直统计到年级
				for (int i = AdminCommon.TABLE_ANALYZE_SCHOOL_LEVEL.length - tenant.getTenant_level()
						- 2; i < AdminCommon.TABLE_ANALYZE_SCHOOL_LEVEL.length - 1; i++)
					levels.add(AdminCommon.TABLE_ANALYZE_SCHOOL_LEVEL[i]);
			}
			int lev = levels.size() - 2; // 统计到倒数第二个等级
			map.put("levels", lev); // 当前登陆单位的等级
		}
		map.put("tenantlevel", tenant.getTenant_level());
		map.put("tenantname", tenant.getTenant_name());
		map.put("tenant_id", tenant.getId());

		Map<String, Object> p_map = new HashMap<String, Object>();
		p_map.put("tenant_id", tenant.getId());
		p_map.put("father_id", 0);
		TenantFrameworks framework = tenantFrameworksService.getFrameworkByName(p_map);
		map.put("frameworkid", framework.getId());
		return map;
//		return new ModelAndView("manager/questionnaire/customerWarningList", map);
	}

	/**
	 * 优化预警程度接口
	 */
	@RequestMapping("/cirsesWarningCounts")
	@ResponseBody
	public Map<String, Object> cirsesWarningCounts(Long tenant_id, String questionnaire_id, String test_begin_date,
			String test_end_date, Double waring_score, Integer datetype) {
		List<String> names = new ArrayList<String>();

		SysTenants tenant = sysTenantsService.getSimpleTenantById(tenant_id);
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> p_map = new HashMap<String, Object>();
		Map<String, Integer> count_map = new HashMap<String, Integer>();
		p_map.put("questionnaire_id", questionnaire_id);

		int lev = 0;

		if (datetype != 0) {
			test_begin_date = DateUtil.dateBack(datetype);
			test_end_date = null;
		}

		if (!StringUtils.isEmpty(test_begin_date)) {
			p_map.put("test_begin_date", test_begin_date);
		}
		if (!StringUtils.isEmpty(test_end_date)) {
			p_map.put("test_end_date", test_end_date);
		}
		p_map.put("waring_score", waring_score);
		// 统计深度，大租户时本登陆单位等级减1，小租户时最小为1，最大为2；
		if (tenant.getTenant_level() == 1) {
			List<Long> frameworkids = new ArrayList<Long>();
			lev = getLevel(tenant_id);
			if (lev == 0) {
				lev = 1;
			}
			if (lev > 2) {
				lev = 2;
			}
			p_map.put("tenant_id", tenant_id);

			List<Map<String, Object>> data = tenantQuestionnaireTaskInfoService.listWarningCounts(p_map);
			// 全体人数
			// todo 查询预警人数
			List<Integer> totalcounts = new ArrayList<>();
			int wcount=0;
			int mcount=0;
			for (int h = 0; h < data.size(); h++) {
				if (Integer.parseInt(data.get(h).get("iswaring").toString()) == 1) {
					wcount += Integer.parseInt(data.get(h).get("count").toString());
				} else {
					mcount += Integer.parseInt(data.get(h).get("count").toString());
				}
			}
			totalcounts.add(wcount + mcount);
			totalcounts.add(wcount);
			map.put("total", totalcounts);

			List<TenantFrameworks> frameworks = getAnalyzeFrameworks(tenant_id, lev);

			for (int i = 0; i < frameworks.size(); i++) {
				int fwcount = 0;
				int fmcount = 0;
				for (int h = 0; h < data.size(); h++) {
					if (data.get(h).get("framework_id").toString().equals(frameworks.get(i).getId().toString())) {
						if (Integer.parseInt(data.get(h).get("iswaring").toString()) == 1) {
							fwcount += Integer.parseInt(data.get(h).get("count").toString());
						} else {
							fmcount += Integer.parseInt(data.get(h).get("count").toString());
						}
					}
				}
				List<Integer> countList = new ArrayList<>();
				TenantFrameworks framework = frameworks.get(i);

				countList.add(fwcount + fmcount);
				countList.add(fwcount);
				String whole_name = framework.getWhole_name();
				String name = whole_name.substring(whole_name.indexOf(tenant.getTenant_name()));
				name = name.replace(tenant.getTenant_name() + "/", "");
				names.add(name);
				frameworkids.add(framework.getId());
				map.put(name, countList);
			}
			map.put("frameworkids", frameworkids);
		} else {

			List<Long> tenantids = new ArrayList<Long>();
			lev = tenant.getTenant_level() - 1;
			List<Long> tenant_ids = this.getSonTenantIds(tenant_id);
			p_map.put("tenant_ids", tenant_ids);

			List<Map<String, Object>> data = tenantQuestionnaireTaskInfoService.listWarningCounts(p_map);
			// 全体人数
			List<Integer> totalcounts = new ArrayList<>();
			int wcount=0;
			int mcount=0;
			for (int h = 0; h < data.size(); h++) {
				if (Integer.parseInt(data.get(h).get("iswaring").toString()) == 1) {
					wcount += Integer.parseInt(data.get(h).get("count").toString());
				} else {
					mcount += Integer.parseInt(data.get(h).get("count").toString());
				}
			}
			totalcounts.add(wcount + mcount);
			totalcounts.add(wcount);
			map.put("total", totalcounts);
			List<SysTenants> tenants = getAnalyzeTenants(tenant.getId(), lev);
			for (int j = 0; j < tenants.size(); j++) {
				int fwcount = 0;
				int fmcount = 0;
				for (int h = 0; h < data.size(); h++) {
					if (data.get(h).get("tenant_id").toString().equals(tenants.get(j).getId().toString())) {
						if (Integer.parseInt(data.get(h).get("iswaring").toString()) == 1) {
							fwcount += Integer.parseInt(data.get(h).get("count").toString());
						} else {
							fmcount += Integer.parseInt(data.get(h).get("count").toString());
						}
					}
				}
				List<Integer> countList = new ArrayList<>();
				countList.add(fwcount + fmcount);
				countList.add(fwcount);
				names.add(tenants.get(j).getTenant_name());
				tenantids.add(tenants.get(j).getId());
				map.put(tenants.get(j).getTenant_name(), countList);
			}
			map.put("tenantids", tenantids);
		}
		map.put("names", names);
		return map;
	}

	/**
	 * 金山教育局 导出统计出来的用户
	 * jsexportExcelUser
	 * exportExcelUser
	 */
	@RequestMapping("/exportExcelUser")

//	public void jsExportExcelUser(String questionnaire_id, String user_name, String real_name, Integer user_gender,
//								  Integer level,Long tenant_id,Long framework_id, Double minScore, Double maxScore, String admin_uuid,
//								  HttpServletRequest request,HttpServletResponse response) throws IOException {
////		User operator = (User) SecurityUtils.getSubject().getPrincipal();
//		AdminUser adminUseoperatorrInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
//		AjaxJson aj = new AjaxJson();
//		String fileName = "userinfoReport";
//		response.setContentType("application/vnd.ms-excel;charset=utf-8");
//		response.setHeader("Content-Disposition",
//				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
//		// 根据传进来的file对象创建可写入的Excel工作薄
//		Map<String, Object> p_map = new HashMap<String, Object>();
//		p_map.put("questionnaire_id", questionnaire_id);
//		if (user_gender != null) {
//			p_map.put("user_gender", user_gender);
//		}
//		if (user_name != null && user_name != "") {
//			p_map.put("user_name", user_name);
//		}
//		if (real_name != null && real_name != "") {
//			p_map.put("real_name", real_name);
//		}
//		p_map.put("minScore", minScore);
//		p_map.put("maxScore", maxScore);
//
//		List<Long> framework_ids = new ArrayList<>();
//		List<Long> tenant_ids = new ArrayList<>();
//
//		if(level == null) {
//			if(tenant_id!=null) {
//				tenant_ids=	this.getSonTenantIds(tenant_id);
//				if(tenant_ids!=null) {
//					tenant_ids.add(tenant_id);
//					p_map.put("tenant_ids", tenant_ids);
//				}else {
//					p_map.put("tenant_id", tenant_id);
//				}
//			}
//			if(framework_id!=null) {
//				TenantFrameworks framework= tenantFrameworksService.getFrameworkById(framework_id);
//				framework_ids = getFrameworkIdsByFatherId(framework_id, framework.getTenant_id());
//				if(framework_ids!=null) {
//					framework_ids.add(framework_id);
//						p_map.put("framework_ids", framework_ids);
//				}else {
//					p_map.put("framework_id", framework_id);
//				}
//			}
//		}else if(level==-1) {
//			// 当登陆单位是大租户并且点击了下级单位时执行此步骤
//			framework_ids = this.getSonTenantIds(framework_id);
//			p_map.put("tenant_ids", framework_ids);
//		}
//		List<Map<String, Object>> data = tenantQuestionnairesService.listUsersByParameter(null,p_map);
//		TenantQuestionnaires mQuestionnaire = tenantQuestionnairesService.findQuestionnaireById(Long.valueOf(questionnaire_id));
//		int mQuestionSum=	mQuestionnaire.getQuestion_sum();
//		List<Map<String, Object>> mQUandAnScoreList = tenantQuestionnaireQuestionService.getQUandAnScore(questionnaire_id);
//		try {
//			if (data.size() != 0) {
//				for (int i = 0; i < data.size(); i++) {
//					String[] dataStr=data.get(i).get("answer").toString().split("\\|");
//					for (int j = 0; j < dataStr.length; j++) {
//						String an=dataStr[j];
//						if(operator.getTop_tenant_id().equals(342L)&&questionnaire_id.equals("46")&&j>=dataStr.length-4) {
//								data.get(i).put("score"+j, an);
//						}else {
//							if(an.contains(",")) {
//								data.get(i).put("score"+j, an);
//							}else {
//								for (int k = 0; k < mQUandAnScoreList.size(); k++) {
//									if((mQUandAnScoreList.get(k).get("qu_id").toString()).equals((1+j)+"")) {
//										if((mQUandAnScoreList.get(k).get("an_id").toString()).equals(an)) {
//											String score = String.valueOf(mQUandAnScoreList.get(k).get("score"));
//											data.get(i).put("score"+j, score);
//										}
//									}
//								}
//							}
//
//						}
//					}
//				}
//				jsWwriteExcel(mQuestionSum,data, response);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		// 日志
//		String operation = operator.getUser_name() + AdminCommon.COMMON_EXPORT + "统计人员信息表";
//		TenantLogs tenantLogs = new TenantLogs();
//		tenantLogs.setUser_uuid(operator.getUuids());
//		tenantLogs.setFramework_id(operator.getTenant_id());
//		tenantLogs.setModule("user");
//		tenantLogs.setOperation(operation);
//		tenantLogsService.insert(tenantLogs);
//		return ;
//	}

	// 导出excel
	public void jsWwriteExcel(int size,List<Map<String, Object>> list, HttpServletResponse response) {
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			WritableWorkbook wwb = null;
			// 创建可写入的Excel工作簿
			wwb = Workbook.createWorkbook(os);
			WritableSheet ws = wwb.createSheet("人员表", 0);
			Label labelName = new Label(0, 0, "用户名");// 表示横着有几个
			Label real_name = new Label(1, 0, "真实姓名");
			Label user_gender = new Label(2, 0, "性别");
			Label user_birth = new Label(3, 0, "出生日期");
			Label frame_work = new Label(4, 0, "组织机构");
			Label score = new Label(5, 0, "总分");
			Label answer = new Label(6, 0, "答案");
			Label submit_date = new Label(7, 0, "提交时间");
				ws.addCell(labelName);
				ws.addCell(real_name);
				ws.addCell(user_gender);
				ws.addCell(user_birth);
				ws.addCell(frame_work);
				ws.addCell(score);
				ws.addCell(answer);
				ws.addCell(submit_date);
			for (int i = 0; i < size; i++) {
				ws.addCell(new Label(8+i, 0, "第"+(i+1)+"题"));
			}

			for (int i = 0; i < list.size(); i++) {
				// System.out.println(list.get(i).get("user_name"));
				Label labelName_i = new Label(0, i + 1, list.get(i).get("user_name").toString());
				Label real_name_i = new Label(1, i + 1, list.get(i).get("real_name").toString());
				Label user_gender_i = new Label(2, i + 1,
						AdminCommon.getGenderString((Integer) list.get(i).get("user_gender")));
				Label user_birth_i = new Label(3, i + 1,
						DateTimeUtil.getStringFromUTC((Long) list.get(i).get("user_birth")));
				Label frame_work_i = new Label(4, i + 1, list.get(i).get("whole_name").toString());
				Label score_i = new Label(5, i + 1, list.get(i).get("score").toString());
				Label answer_i = new Label(6, i + 1, list.get(i).get("answer").toString());
				Label submit_date_i = new Label(7, i + 1, list.get(i).get("submit_date").toString());
				ws.addCell(labelName_i);
				ws.addCell(real_name_i);
				ws.addCell(user_gender_i);
				ws.addCell(user_birth_i);
				ws.addCell(frame_work_i);
				ws.addCell(score_i);
				ws.addCell(answer_i);
				ws.addCell(submit_date_i);
				for (int j = 0; j < size; j++) {
					ws.addCell(new Label(8+j, i + 1, list.get(i).get("score"+j)==null?"未选择":list.get(i).get("score"+j)+""));
				}
			}
			// 写进文档
			wwb.write();
			wwb.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(os);
		}
	}
}
